import { defineStore } from "pinia";
import { store } from "@/store";
import type { tasksFace } from "@/types/tasks"
import { getList,upDate,Create,Delete } from "@/api/tasks"
import { ElMessage } from "element-plus";
interface StoreState {
    loding: boolean,
    page: number,
    pageSize: number,
    querys: any,
    total: number,
    list: tasksFace[],
}
const appStore = defineStore({
    id: "tasks",
    state: (): StoreState => ({
        loding: false,
        page: 1,
        pageSize: 20,
        total: 0,
        querys: {},
        list: []
    }),
    getters: {
        getList(): tasksFace[] {
            return this.list
        },
        getLoding(): boolean {
            return this.loding
        },
        getPage(): number {
            return this.page
        },
        getPageSize(): number {
            return this.pageSize
        },
        getTotal(): number {
            return this.total
        }
    },
    actions: {
        setLoding(l: boolean) {
            this.loding = l
        },
        setQuerys(o: any) {
            this.querys = o;
            this.LoadList();
        },
        setPageSize(pageSize: number) {
            this.pageSize = pageSize
            this.LoadList()
        },
        setPage(page: number) {
            this.page = page
            this.LoadList()
        },
        setTotal(page: number) {
            this.page = page

        },
        async LoadList() {
            this.loding = true
            try {
                const res: {
                    list: tasksFace[],
                    total: number,
                } = await getList({
                    page: this.page,
                    pageSize: this.pageSize,
                    ...this.querys
                })
                if (res) {
                    this.list = res.list
                    this.total = res.total
                }
            } catch (error) {

            } finally {
                this.loding = false
            }
        },
        refresh() {
            this.page = 1;
            this.loding = false;
            this.querys = {};
            this.total = 0;
            this.list = [];
          },
          async addOrupDate(e: tasksFace) {
            try {
              if (e.id) {
                await upDate(e);
              } else {
                await Create(e);
              }
              ElMessage.success("操作成功");
              this.LoadList();
            } catch (error) {
              ElMessage.error(error);
            }
          },
          async remove(uuid: string|number) {
            try {
              await Delete({ uuid });
              ElMessage.success("操作成功");
              this.LoadList();
            } catch (error) {
              ElMessage.error(error);
            }
          },

    },
})
export function useTasksStoreWithOut() {
    return appStore(store);
}